<script setup lang="ts">
import { reactive, ref, toRaw } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useQuery } from "@/hooks/init";
import { useShare } from "@/hooks/share";
import { useSwipe } from "@/hooks/swipe";
import { header_api, index_api } from "@/package/other/api/tour_word";
import { AppData } from "@/utils/app";
import { Router } from "@/utils/router";
import { Toast } from "@/utils/toast";

import NavBack from "@/components/nav/back.vue";
import NavBg from "@/components/nav/bg.vue";
import NavSpace from "@/components/nav/space.vue";
import IndexSearchBar from "./components/index-search-bar.vue";
import IndexTypeItem from "./components/index-type-item.vue";
import IndexAdItem from "./components/index-ad-item.vue";
import ListEmpty from "@/components/list/empty.vue";
import IndexInterpretationItem from "./components/index-interpretation-item.vue";

onLoad((options) => {
  useQuery(options as MiniApp.AppLaunchOption, () => {
    header_api().then((resp) => {
      const _typeList: any[][] = [[], []];
      resp.cate.forEach((i, d) => _typeList[d % 2].push(i));
      typeList.value = _typeList;

      if (resp.cate.length > 0) {
        typeClick(resp.cate[0].id);
      }
    });

    shareOption.title = "名词解释";
  });
});

const queryData = reactive({ keyword: "", cate_id: "" });
const searchStatus = ref<"init" | "finish">("init"); // search：搜索中（聚焦）, finish：搜索完成
const searchClick = (type: "search" | "clear") => {
  if (type === "search") {
    const keyword = queryData.keyword.trim();
    if (!keyword) return;
    Toast.showLoading();
    index_api({ page: 1, page_size: 1000, keyword })
      .then((resp) => {
        interpretationList.value = resp.items;
        searchStatus.value = "finish";
        Toast.hideLoading();
      })
      .catch(() => Toast.hideLoading());
  } else {
    queryData.keyword = "";
    searchStatus.value = "init";
  }
};

const typeList = ref<any[][]>([]);
const typeClick = (id: string) => {
  queryData.cate_id = id;
  index_api({ page: 1, page_size: 1000, cate_id: id }).then((resp) => {
    swipeData.current = 0;
    adList.value = resp.items.map((i) => {
      return { ...i, name_arr: i.name.split("") };
    });
  });
};

const adList = ref<any[]>([]);
const adClick = (index: number) => {
  Router.navigateTo("/package/other/pages/interpretation/detail", (resp) => {
    resp.eventChannel.emit(
      "ev-interpretation-data",
      toRaw(adList.value)[index]
    );
  });
};

const interpretationList = ref<any[]>([]);
const interpretationClick = (index: number) => {
  Router.navigateTo("/package/other/pages/interpretation/detail", (resp) => {
    resp.eventChannel.emit(
      "ev-interpretation-data",
      toRaw(interpretationList.value)[index]
    );
  });
};

const { swipeData, swipeChange } = useSwipe();

const { onShareAppMessage, onShareTimeline, shareOption } = useShare(
  "/package/other/pages/interpretation/index"
);
</script>

<template>
  <NavBack />
  <NavBg url="/package/other/static/interpretation-bg.png" />
  <NavSpace />

  <image
    class="index-title"
    src="@/package/other/static/interpretation-index-title.png"
  />

  <IndexSearchBar
    v-model="queryData.keyword"
    :status="searchStatus"
    @search="searchClick"
  />

  <template v-if="searchStatus === 'init'">
    <scroll-view class="index-type" scroll-x enhanced :show-scrollbar="false">
      <view class="index-type-space"></view>
      <view class="index-type-row" v-for="(i, d) of typeList" :key="d">
        <view
          class="index-type-item"
          v-for="j of i"
          :key="j.id"
          @click="typeClick(j.id)"
        >
          <IndexTypeItem
            :isActive="queryData.cate_id === j.id"
            :text="`${j.name} ${j.count}`"
          />
        </view>
      </view>
    </scroll-view>

    <swiper
      class="index-ad"
      :current="swipeData.current"
      circular
      previous-margin="80rpx"
      next-margin="80rpx"
      @change="swipeChange"
    >
      <swiper-item v-for="(i, d) of adList" :key="i.id">
        <view
          class="index-ad-item"
          :style="{
            transform: swipeData.index === d ? '' : 'scale(0.8644)',
            opacity: swipeData.index === d ? '' : 0.6,
          }"
          @click="adClick(d)"
        >
          <IndexAdItem :info="i" :index="`${d + 1}/${adList.length}`" />
        </view>
      </swiper-item>
    </swiper>
  </template>

  <scroll-view
    class="index-data"
    v-else
    :style="{
      height: `calc(100vh - ${AppData.rectData.topBarHeight}px - 262rpx)`,
    }"
    scroll-y
  >
    <view class="index-data-empty" v-if="interpretationList.length === 0">
      <ListEmpty text="抱歉，该名词暂未收录呢~~" translateY="-10%" />
    </view>

    <view class="index-data-wrapper" v-else>
      <view
        class="index-data-item"
        v-for="(i, d) of interpretationList"
        :key="i.id"
        @click="interpretationClick(d)"
      >
        <IndexInterpretationItem :info="i" />
      </view>
    </view>
  </scroll-view>
</template>

<style lang="scss">
page {
  padding-top: 30rpx;
  padding-bottom: 0;
  background-color: #fdf5e7;
}

.index-title {
  position: relative;
  display: block;
  width: 332rpx;
  height: 62rpx;
  margin-left: 68rpx;
  margin-bottom: 40rpx;
}

.index-type {
  height: 176rpx;
  margin-top: 10rpx;
  margin-bottom: 26rpx;
  white-space: nowrap;

  .index-type-space {
    height: 20rpx;
  }

  .index-type-row {
    padding-left: 30rpx;
  }

  .index-type-item {
    display: inline-block;
    margin-right: 20rpx;
    margin-bottom: 16rpx;
    vertical-align: top;
  }
}

.index-ad {
  height: 886rpx;

  .index-ad-item {
    height: 100%;
    transition: all 0.3s ease-out;
  }
}

.index-data {
  margin-top: 50rpx;

  .index-data-empty {
    height: 486rpx;
    margin: 130rpx 40rpx 0;
    border-radius: 20rpx;
    border: 2rpx solid #b95c47;
    background-color: rgba(255, 255, 255, 0.8);
  }

  .index-data-wrapper {
    padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  }

  .index-data-item {
    margin: 0 40rpx 20rpx;
  }
}
</style>